package com.szholly.pro.watergas_server.ps.android.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.szholly.pro.watergas_server.common.data.DataUtil;
import com.szholly.pro.watergas_server.ps.android.bean.QcTaskParam;
import com.szholly.pro.watergas_server.ps.android.common.DateTime;
import com.szholly.pro.watergas_server.ps.android.common.FieldInterceptor;
import com.szholly.pro.watergas_server.ps.android.common.NonNullUtil;
import com.szholly.pro.watergas_server.ps.android.common.SecurityConfig;
import com.szholly.pro.watergas_server.ps.android.common.SqlUtils;
import com.szholly.pro.watergas_server.ps.android.common.TableRowMap;
import com.szholly.pro.watergas_server.ps.android.common.ValidUtils;
import com.szholly.pro.watergas_server.ps.android.controller.QcControl;
import com.szholly.pro.watergas_server.ps.android.controller.QcService;
import com.szholly.pro.watergas_server.ps.data.QcLocaleCheckContentTable;
import com.szholly.pro.watergas_server.water.localcheck.QcLocalecheckRow;
import com.szholly.data.general.GlobalParameter;
import com.szholly.data.general.RowBase;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class QcTaskLocaleCheckStrategy extends QcTaskStrategy {
	private List<RowBase> mResultStatusList;
	private QcService mDomainManager = QcService.get();

	public QcTaskLocaleCheckStrategy(QcOperationService mOperationService) {
		super(mOperationService);
	}

	@Override
	public List<RowBase> getTaskList(QcTaskParam taskParam) throws Exception {
		return mOperationService.getOperationTaskList(taskParam);
	}

	@Override
	public RowBase addTask(QcTaskParam taskParam) throws Exception {
		return mOperationService.addOperationTask(taskParam);
	}

	@Override
	public void deleteTask(QcTaskParam taskParam) throws Exception {
		mOperationService.deleteOperationTask(taskParam);
	}

	private void executeDeleteTaskContent(String taskCode) {
		List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
		parms.add(new GlobalParameter("taskCode", taskCode));
		String childDeleteSql = "delete from qc_locale_check_content t\n"
				+ " where t.father_id in (select t1.guid\n"
				+ "                         from qc_localecheck t1\n"
				+ "                        where t1.operation_task_code = @taskCode)";
		String mainDeleteSql = "delete from QC_LOCALECHECK t where t.operation_task_code = @taskCode";
		DataUtil.ExecuteUpdateSql(childDeleteSql, parms);
		DataUtil.ExecuteUpdateSql(mainDeleteSql, parms);
	}

	@Override
	public void deleteProcessedTask(QcTaskParam taskParam) throws Exception {
		String userId = taskParam.getUserId();
		String taskCode = taskParam.getTaskCode();

		SecurityConfig config = SecurityConfig.get(userId);
		ValidUtils.isTrue(config.containQcDeleteProcessedTask, "权限不够");
		try {
			DataUtil.beginTransaction();
			executeDeleteTaskContent(taskCode);
			mOperationService.deleteOperationTask(taskParam);
			DataUtil.commitTransaction();
		} catch (Exception e) {
			DataUtil.rollbackTransaction();
			throw e;
		}
	}

	@Override
	public RowBase getProcessedTaskInitData(QcTaskParam taskParam) throws Exception {
		String userId = taskParam.getUserId();
		String taskTypeCode = taskParam.getTaskTypeCode();
		String domainTableCode = QcControl.getDomainTableCode(taskTypeCode, taskParam.getCompanyCode());
		String taskCode = taskParam.getTaskCode();
		List<RowBase> tableFieldList = getTableContentList(domainTableCode);
		List<RowBase> resultList = getResultStatusList();
		List<RowBase> childList = getChildTableRow(taskCode);
		List<RowBase> projectList = getProjectList();

		Map<String, RowBase> childValueMap = new HashMap<>();
		for (RowBase rowBase : childList) {
			childValueMap.put(rowBase.getSafeString("id"), rowBase);
		}

		RowBase tableTitleRow = getTableTitle(domainTableCode);

		// 分割成两种List
		List<RowBase> editList = new ArrayList<RowBase>();
		List<RowBase> checkList = new ArrayList<RowBase>();
		for (RowBase bean : tableFieldList) {
			String id = String.valueOf(bean.get("id"));
			String fatherName = (String) bean.get("fatherName");
			if (childValueMap.containsKey(id)) {
				RowBase rowBase = childValueMap.get(id);
				String status = rowBase.getSafeString("status");
				String remark = rowBase.getSafeString("remark");
				bean.put("value", status);
				bean.put("detail", remark);
			} else {
				bean.put("value", "1");// 默认全部选中
			}
			if ("文本".equals(fatherName)) {
				editList.add(bean);
			} else {
				checkList.add(bean);
			}
		}
		String companyCode = getCompanyCode(userId);
		List<RowBase> personList = null;
		if ("1".equals(companyCode)) {// 表示浩瑞泰公司成员
			personList = mDomainManager.getPersonList("3");
		} else {
			personList = mDomainManager.getPersonList(companyCode, "3");
		}
		RowBase mainTableRow = getMainTableRow(taskCode);

		RowBase resultMap = new RowBase();
		resultMap.put("editList", editList);
		resultMap.put("checkList", checkList);
		resultMap.put("personList", personList);
		resultMap.put("resultList", resultList);
		resultMap.put("tableTitle", tableTitleRow.getSafeString("s_domaincaption"));
		resultMap.put("tableTitleId", tableTitleRow.getSafeString("s_domaincode"));
		resultMap.put("projectList", projectList);

		resultMap.put("dateTime", mainTableRow.getSafeString("dateTime"));
		resultMap.put("checkPerson", mainTableRow.getSafeString("checksign"));
		resultMap.put("checkedPerson", mainTableRow.getSafeString("checkunitsign"));
		resultMap.put("photo", mainTableRow.getSafeString("photo"));
		resultMap.put("resultStatus", mainTableRow.getSafeString("result_status"));
		resultMap.put("result", mainTableRow.getSafeString("result"));
		resultMap.put("project", mainTableRow.getSafeString("project"));
		return resultMap;
	}

	@Override
	public RowBase getTaskInitData(QcTaskParam taskParam) throws Exception {
		String userId = taskParam.getUserId();
		String taskTypeCode = taskParam.getTaskTypeCode();
		String domainTableCode = QcControl.getDomainTableCode(taskTypeCode, taskParam.getCompanyCode());
		List<RowBase> tableFieldList = getTableContentList(domainTableCode);
		List<RowBase> resultList = getResultStatusList();
		List<RowBase> projectList = getProjectList();

		RowBase tableTitleRow = getTableTitle(domainTableCode);

		// 分割成两种List
		List<RowBase> editList = new ArrayList<RowBase>();
		List<RowBase> checkList = new ArrayList<RowBase>();
		for (RowBase bean : tableFieldList) {
			String fatherName = (String) bean.get("fatherName");
			if ("文本".equals(fatherName)) {
				editList.add(bean);
			} else {
				bean.put("value", "1");// 默认全部选中
				checkList.add(bean);
			}
		}
		String companyCode = getCompanyCode(userId);
		List<RowBase> personList = null;
		if ("1".equals(companyCode)) {// 表示浩瑞泰公司成员
			personList = mDomainManager.getPersonList("3");
		} else {
			personList = mDomainManager.getPersonList(companyCode, "3");
		}

		RowBase resultMap = new RowBase();
		resultMap.put("editList", editList);
		resultMap.put("checkList", checkList);
		resultMap.put("personList", personList);
		resultMap.put("resultList", resultList);
		resultMap.put("projectList", projectList);
		resultMap.put("tableTitle", tableTitleRow.getSafeString("s_domaincaption"));
		resultMap.put("tableTitleId", tableTitleRow.getSafeString("s_domaincode"));

		resultMap.put("dateTime", new DateTime().toString("yyyy-MM-dd HH:mm:ss"));
		return resultMap;
	}

	private List<RowBase> getProjectList() throws Exception{
		String sql = "select t.s_domaincode \"id\", t.s_domaincaption \"name\"\n"
				+ "  from data_defulatdomain t\n"
				+ " where t.s_domainname = '质控委托项目'\n"
				+ "   and t.i_jb = '2'";
		List<RowBase> rows = DataUtil.getSelectRows(sql, null);
		ValidUtils.notEmpty(rows, "委托项目数据为空");
		return NonNullUtil.toList(rows);
	}

	private RowBase getTableTitle(String domainTableCode) throws Exception {
		List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
		parms.add(new GlobalParameter("domainTableCode", domainTableCode));
		String sql = "select t.s_domaincaption , t.s_domaincode \n"
				+ "  from data_defulatdomain t\n"
				+ " where t.s_domainname = '质控现场考核'\n"
				+ "   and t.s_domaincode = @domainTableCode";
		List<RowBase> rows = DataUtil.getSelectRows(sql, parms);
		ValidUtils.notEmpty(rows, "表标题无法获取");
		return rows.get(0);
	}

	@Override
	public void saveTask(QcTaskParam taskParam) throws Exception {
		String data = taskParam.getData();
		JSONObject json = JSONObject.fromObject(data);
		List<TableRowMap> insertList = parseToSaveList(json);

		JSONObject taskJson = json.getJSONObject("taskBean");
		String TASK_CODE = taskJson.optString("TASK_CODE");
		String TASK_DESC = taskJson.optString("TASK_DESC");

		try {
			DataUtil.beginTransaction();

			preFinishOperationTask(TASK_CODE, TASK_DESC);
			SqlUtils.prepareInsert(insertList);
			DataUtil.commitTransaction();
		} catch (Exception e) {
			DataUtil.rollbackTransaction();
			throw e;
		}
	}

	@Override
	public void updateTask(QcTaskParam taskParam) throws Exception {
		String data = taskParam.getData();
		JSONObject json = JSONObject.fromObject(data);
		List<TableRowMap> insertList = parseToSaveList(json);

		JSONObject taskJson = json.getJSONObject("taskBean");
		String taskCode = taskJson.optString("TASK_CODE");
		String taskDesc = taskJson.optString("TASK_DESC");
		try {
			DataUtil.beginTransaction();
			executeDeleteTaskContent(taskCode);
			preFinishOperationTask(taskCode, taskDesc);
			SqlUtils.prepareInsert(insertList);
			DataUtil.commitTransaction();
		} catch (Exception e) {
			DataUtil.rollbackTransaction();
			throw e;
		}
	}

	private List<TableRowMap> parseToSaveList(JSONObject data) throws Exception {
		JSONArray fatherArray = data.getJSONArray("fatherList");
		JSONArray childArray = data.getJSONArray("childList");

		// 生成表单列表
		FieldInterceptor fieldInterceptor = FieldInterceptor.createNotNullInterceptor(QcLocalecheckRow.FIELD_Checksign, QcLocalecheckRow.FIELD_Photo);
		List<TableRowMap> mainTableList = TableRowMap.get(fatherArray, "QC_LOCALECHECK");
		for (TableRowMap bean : mainTableList) {
			bean.setFieldInterceptor(fieldInterceptor);
			String contentId = (String) bean.get(QcLocalecheckRow.FIELD_CheckContent);
			bean.put(QcLocalecheckRow.FIELD_CheckType, contentId.substring(0, contentId.length() - 2));
		}
		List<TableRowMap> childTableList = TableRowMap.get(childArray, QcLocaleCheckContentTable.TABLE_NAME);
		List<TableRowMap> insertList = new ArrayList<>();
		insertList.addAll(mainTableList);
		insertList.addAll(childTableList);
		return insertList;
	}

	private List<RowBase> getChildTableRow(String taskCode) {
		List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
		parms.add(new GlobalParameter("taskCode", taskCode));
		String sql = "select t.ID, t.status, t.remark\n"
				+ "  from qc_locale_check_content t\n"
				+ "  left join qc_localecheck t1\n"
				+ "    on t1.guid = t.father_id\n"
				+ " where 1 = 1\n"
				+ "   and t1.operation_task_code = @taskCode";
		List<RowBase> rows = DataUtil.getSelectRows(sql, parms);
		return rows;
	}

	private RowBase getMainTableRow(String taskCode) throws Exception {
		List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
		parms.add(new GlobalParameter("taskCode", taskCode));
		String sql = "select to_char(t.checkdate, 'yyyy-mm-dd hh24:mi:ss') dateTime,\n"
				+ "       t.checksign,\n"
				+ "       t.checkunitsign,\n"
				+ "       t.photo,\n"
				+ "       t.result_status,\n"
				+ "       t.result\n"
				+ "  from QC_LOCALECHECK t\n"
				+ " where 1 = 1"
				+ "   and t.operation_task_code = @taskCode";
		List<RowBase> rows = DataUtil.getSelectRows(sql, parms);
		ValidUtils.notEmpty(rows, "主表数据为空");
		return rows.get(0);
	}

	// 获取表结构信息,RowBase包含三个字段 name(字段注释)、id(字段名)、type(字段类型)
	private List<RowBase> getTableContentList(String tableCode) {
		List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
		parms.add(new GlobalParameter("tableCode", tableCode + "%"));
		String sql = "select t.s_domaincode     \"id\",\n"
				+ "       t.s_domaincaption  \"name\",\n"
				+ "       t1.s_domaincaption \"fatherName\"\n"
				+ "  from data_defulatdomain t\n"
				+ "  left join data_defulatdomain t1\n"
				+ "    on t1.s_domainname = '质控现场考核'\n"
				+ "   and t1.i_jb = '4'\n"
				+ "   and t1.s_domaincode like @tableCode\n"
				+ "   and t.s_pid = t1.s_id\n"
				+ " where t.s_domainname = '质控现场考核'\n"
				+ "   and t.i_jb = '5'\n"
				+ "   and t.s_domaincode like @tableCode\n"
				+ " order by t1.i_order,t.i_order";
		List<RowBase> rows = DataUtil.getSelectRows(sql, parms);
		return rows;
	}

	private String getCompanyCode(String userId) throws Exception {
		ValidUtils.hasText(userId, "用户编号为空");
		List<GlobalParameter> parms = new ArrayList<>();
		parms.add(new GlobalParameter("userId", userId));
		String sql = "select t.s_orgid from safe_user t where t.s_userid = @userId";
		List<RowBase> rows = DataUtil.getSelectRows(sql, parms);
		ValidUtils.notEmpty(rows, "无法通过用户编号获取公司编号");
		String companyCode = rows.get(0).getSafeString("s_orgid");
		ValidUtils.hasText(companyCode, "公司编号为空");
		return companyCode;
	}

	synchronized private List<RowBase> getResultStatusList() {
		if (mResultStatusList == null) {
			mResultStatusList = new ArrayList<>();
			RowBase row;
			row = new RowBase();
			row.put("id", "0");
			row.put("name", "质控工作总体处于受控状态");
			mResultStatusList.add(row);
			row = new RowBase();
			row.put("id", "1");
			row.put("name", "质控工作总体需要加强");
			mResultStatusList.add(row);
			row = new RowBase();
			row.put("id", "2");
			row.put("name", "质控工作存在失效问题");
			mResultStatusList.add(row);
		}
		return mResultStatusList;
	}
}
